package com.lancoo.znbkxx.teacher.aibkTestCoach.paperToPreview

import android.app.Activity
import android.content.Intent
import android.os.Handler
import android.text.Html
import android.text.TextPaint
import android.view.View
import androidx.fragment.app.Fragment
import androidx.viewpager.widget.ViewPager
import com.lancoo.znbkxx.teacher.R
import com.lancoo.znbkxx.teacher.aibkTestCoach.aibkDialog.ShowDialogTools
import com.lancoo.znbkxx.teacher.aibkTestCoach.aibkPublicActivity.ActivityErrorRecovery
import com.lancoo.znbkxx.teacher.aibkTestCoach.aibkTools.LancooMethod
import com.lancoo.znbkxx.teacher.aibkTestCoach.aibkTools.MyToast
import com.lancoo.znbkxx.teacher.aibkTestCoach.kBase.KBaseActivity
import com.lancoo.znbkxx.teacher.aibkTestCoach.kBase.KBaseFragmentPagerAdapter
import com.lancoo.znbkxx.teacher.aibkTestCoach.networkRequest.bindLifeCycle
import com.lancoo.znbkxx.teacher.aibkTestCoach.networkRequest.entity.PaperPreviewInfor
import com.lancoo.znbkxx.teacher.aibkTestCoach.networkRequest.viewModel.MarkViewModel
import com.lancoo.znbkxx.teacher.aibkTestCoach.paperToPreview.AibkPreviewAnswerSheetDialog.onClickDialogListener
import com.lancoo.znbkxx.teacher.aibkTestCoach.paperToPreview.aibkPreviewDXT.PreviewFragmentDxt
import com.lancoo.znbkxx.teacher.aibkTestCoach.paperToPreview.aibkPreviewFHXZ.PreviewFragmentFhxz
import com.lancoo.znbkxx.teacher.aibkTestCoach.paperToPreview.aibkPreviewGCT.PreviewFragmentGct
import com.lancoo.znbkxx.teacher.aibkTestCoach.paperToPreview.aibkPreviewJDT.PreviewFragmentJdt
import com.lancoo.znbkxx.teacher.aibkTestCoach.paperToPreview.aibkPreviewPPT.PreviewFragmentPpt
import com.lancoo.znbkxx.teacher.aibkTestCoach.paperToPreview.aibkPreviewTKT.PreviewFragmentTkt
import com.lancoo.znbkxx.teacher.aibkTestCoach.paperToPreview.aibkPreviewWXXZ.PreviewFragmentWxxz
import com.lancoo.znbkxx.teacher.aibkTestCoach.paperToPreview.aibkPreviewXZT.PreviewFragmentXzt
import com.lancoo.znbkxx.teacher.aibkTestCoach.paperToPreview.aibkPreviewYDPP.PreviewFragmentYdpp
import com.lancoo.znbkxx.teacher.aibkTestCoach.paperToPreview.aibkPreviewZHT.PreviewFragmentZht
import com.lancoo.znbkxx.teacher.aibkTestCoach.paperToPreview.aibkPreviewZW.PreviewFragmentZw
import com.lancoo.znbkxx.teacher.utils.DensityUtils
import kotlinx.android.synthetic.main.aibk_activity_paper_preview.*
import kotlinx.android.synthetic.main.aibk_include_loading_refresh.*
import org.koin.androidx.viewmodel.ext.android.viewModel

class AibkPaperPreviewActivity : KBaseActivity(), View.OnClickListener {

    companion object {
        fun launch(activity: Activity, paperId: String, setId: String, isOneOnOne: Boolean) {
            val intent = Intent(activity, AibkPaperPreviewActivity::class.java)
            intent.putExtra("PaperID", paperId)
            intent.putExtra("SetID", setId)
            intent.putExtra("IsOneOnOne", isOneOnOne)
            activity.startActivity(intent)
        }
    }

    private var quesScoreInfor = ""
    private var isFullOneLine = false
    private var typeListPosition = 0
    private var quesListPosition = 0
    private var vpQuesPosition = 0
    private val mViewModel: MarkViewModel by viewModel()
    private var paperPreviewInfor: PaperPreviewInfor? = null
    private var fragmentList: MutableList<Fragment>? = ArrayList()

    override fun setLayout(): Int {
        return R.layout.aibk_activity_paper_preview
    }

    override fun initView() {
        BtnBack.setOnClickListener(this)
        SBtnErrorRecovery.setOnClickListener(this)
        SBtnAnswerSheet.setOnClickListener(this)
        LlToolsView.visibility = View.GONE
        TvQuesInfor.visibility = View.GONE
        TvQuesInfor.setOnClickListener(this)
    }

    override fun initData() {
        val paperId = intent.getStringExtra("PaperID")
        val setId = intent.getStringExtra("SetID")
        val isOneOnOne = intent.getBooleanExtra("IsOneOnOne", false)
        if (isOneOnOne) {
            mViewModel.getPreviewPaperInfo_1v1(paperId, setId)
                    .doOnSubscribe {
                        RlGifLoading.visibility = View.VISIBLE
                    }.bindLifeCycle(this)
                    .subscribe({
                        if (it.code == 1) {
                            RlGifLoading.visibility = View.GONE
                            paperPreviewInfor = it.data
                            showPreviewPaperView(paperPreviewInfor!!)
                        } else {
                            MyToast.showToast(it.message)
                            Handler().postDelayed({
                                finish()
                            }, 1000)
                        }
                    }, {
                        MyToast.showToast(it.message)
                        Handler().postDelayed({
                            finish()
                        }, 1000)
                    })
        } else {
            mViewModel.getPaperPreviewInfor(paperId, setId)
                    .doOnSubscribe {
                        RlGifLoading.visibility = View.VISIBLE
                    }.bindLifeCycle(this)
                    .subscribe({
                        if (it.code == 1) {
                            RlGifLoading.visibility = View.GONE
                            paperPreviewInfor = it.data
                            showPreviewPaperView(paperPreviewInfor!!)
                        } else {
                            MyToast.showToast(it.message)
                            Handler().postDelayed({
                                finish()
                            }, 1000)
                        }
                    }, {
                        MyToast.showToast(it.message)
                        Handler().postDelayed({
                            finish()
                        }, 1000)
                    })
        }

    }

    private fun showPreviewPaperView(paperPreviewInfor: PaperPreviewInfor) {
        //显示试卷名称以及答题卡按钮
        LlToolsView.visibility = View.VISIBLE
        val paperName = paperPreviewInfor.PaperName
        val setName = paperPreviewInfor.SetName
        TvPaperName.text = "$paperName($setName)的预览"
        TvQuesInfor.visibility = View.VISIBLE

        //加载试题,显示试卷作答情况
        fragmentList?.clear()
        var typeListSize = paperPreviewInfor.TypeList.size
        for (i in 0 until typeListSize) {
            var typeNo = paperPreviewInfor.TypeList[i].TypeNo
            var quesListSize = paperPreviewInfor.TypeList[i].QuesList.size
            for (j in 0 until quesListSize) {
                if (typeNo == "A") {
                    val mFragment = PreviewFragmentDxt(this, paperPreviewInfor, i, j)
                    (fragmentList as ArrayList<Fragment>).add(mFragment)
                } else if (typeNo == "C") {
                    val mFragment = PreviewFragmentWxxz(this, paperPreviewInfor, i, j)
                    (fragmentList as ArrayList<Fragment>).add(mFragment)
                } else if (typeNo == "L" || typeNo == "E" || typeNo == "F" || typeNo == "D") {//听力选择，听力判断，阅读选择
                    val mFragment = PreviewFragmentXzt(this, paperPreviewInfor, i, j)
                    (fragmentList as ArrayList<Fragment>).add(mFragment)
                } else if (typeNo == "k") {
                    val mFragment = PreviewFragmentZht(this, paperPreviewInfor, i, j)
                    (fragmentList as ArrayList<Fragment>).add(mFragment)
                } else if (typeNo == "H") {
                    val mFragment = PreviewFragmentFhxz(this, paperPreviewInfor, i, j)
                    (fragmentList as ArrayList<Fragment>).add(mFragment)
                } else if (typeNo == "f") {
                    val mFragment = PreviewFragmentZw(this, paperPreviewInfor, i, j)
                    (fragmentList as ArrayList<Fragment>).add(mFragment)
                } else if (typeNo == "N" || typeNo == "S") { //N:普通填空题  S：听力填空题
                    val mFragment = PreviewFragmentTkt(this, paperPreviewInfor, i, j)
                    (fragmentList as ArrayList<Fragment>).add(mFragment)
                } else if (typeNo == "Q" || typeNo == "b" || typeNo == "d"
                        || typeNo == "X" || typeNo == "g" || typeNo == "V"
                        || typeNo == "G") {//Q:阅读填空,X:阅读简答,G:听力简答,
                    val mFragment = PreviewFragmentJdt(this, paperPreviewInfor, i, j)
                    (fragmentList as ArrayList<Fragment>).add(mFragment)
                } else if (typeNo == "x" || typeNo == "m") {//x:听力匹配,m:普通匹配题
                    val mFragment = PreviewFragmentPpt(this, paperPreviewInfor, i, j)
                    (fragmentList as ArrayList<Fragment>).add(mFragment)
                } else if (typeNo == "U") {
                    val mFragment = PreviewFragmentGct(this, paperPreviewInfor, i, j)
                    (fragmentList as ArrayList<Fragment>).add(mFragment)
                } else if (typeNo == "P") {
                    val mFragment = PreviewFragmentYdpp(this, paperPreviewInfor, i, j)
                    (fragmentList as ArrayList<Fragment>).add(mFragment)
                }
            }
        }

        val mAdapter = KBaseFragmentPagerAdapter(supportFragmentManager, fragmentList as ArrayList<Fragment>)
        VpPreview.adapter = mAdapter

        //处理viewpager滑动事件
        VpPreview.addOnPageChangeListener(object : ViewPager.OnPageChangeListener {
            override fun onPageScrolled(
                    position: Int,
                    positionOffset: Float,
                    positionOffsetPixels: Int
            ) {
            }

            override fun onPageSelected(position: Int) {
                vpQuesPosition = position
                showQuesTitleInfor(paperPreviewInfor)
            }

            override fun onPageScrollStateChanged(state: Int) {}
        })

        showQuesTitleInfor(paperPreviewInfor)
    }

    private fun showQuesTitleInfor(paperPreviewInfor: PaperPreviewInfor) {
        typeListPosition = PreviewInforIndexHelp.QuesPosition_return_TypeListPosition(paperPreviewInfor, vpQuesPosition)

        val typeIndex = paperPreviewInfor.TypeList[typeListPosition].TypeIndex
        val strTypeIndex = LancooMethod.numberToChinese(typeIndex)
        var genreName = paperPreviewInfor.TypeList[typeListPosition].GenreName
        val typeName = paperPreviewInfor.TypeList[typeListPosition].TypeName
        if (genreName.isEmpty()) {
            genreName = typeName
        }
        /******************************************************************************************/
        var totalChildQuesSize = 0
        var totalChildQuesScore = 0.0
        val quesListSize = paperPreviewInfor.TypeList[typeListPosition].QuesList.size
        for (i in 0 until quesListSize) {
            val sortIndexListSize = paperPreviewInfor.TypeList[typeListPosition].QuesList[i].SortIndexList.size
            totalChildQuesSize += sortIndexListSize

            for (j in 0 until sortIndexListSize) {
                val score = paperPreviewInfor.TypeList[typeListPosition].QuesList[i].SortIndexList[j].Score
                totalChildQuesScore += score
            }
        }

        var isAverage = true
        val averageScore = LancooMethod.getCorrectRateInt(totalChildQuesScore, totalChildQuesSize)
        outLoop@ for (i in 0 until quesListSize) {
            val sortIndexListSize = paperPreviewInfor.TypeList[typeListPosition].QuesList[i].SortIndexList.size
            for (j in 0 until sortIndexListSize) {
                val score = paperPreviewInfor.TypeList[typeListPosition].QuesList[i].SortIndexList[j].Score
                if (score != averageScore) {
                    isAverage = false
                    break@outLoop
                }
            }
        }

        if (isAverage) {
            isFullOneLine = false
            val strAverageScore = LancooMethod.killlingDouble(averageScore)
            TvQuesInfor.text = Html.fromHtml(resources.getString(R.string.aibk_practice_ques_infor_short,
                    strTypeIndex, genreName, quesListSize, totalChildQuesSize, strAverageScore))
        } else {
            isFullOneLine = true
            var childScoreAll = ""
            val quesListSize = paperPreviewInfor.TypeList[typeListPosition].QuesList.size
            for (x in 0 until quesListSize) {
                val sortIndexListSize = paperPreviewInfor.TypeList[typeListPosition].QuesList[x].SortIndexList.size
                for (y in 0 until sortIndexListSize) {
                    val sortIndex = paperPreviewInfor.TypeList[typeListPosition].QuesList[x].SortIndexList[y].SortIndex
                    val score = paperPreviewInfor.TypeList[typeListPosition].QuesList[x].SortIndexList[y].Score
                    val strScore = LancooMethod.killlingDouble(score)
                    val childScore = resources.getString(R.string.aibk_single_ques_infor, sortIndex, strScore)
                    if (childScoreAll.isEmpty()) {
                        childScoreAll = childScore
                    } else {
                        childScoreAll = "$childScoreAll,$childScore"
                    }
                }
            }
            TvQuesInfor.text = Html.fromHtml(resources.getString(R.string.aibk_practice_ques_infor_long,
                    strTypeIndex, genreName, quesListSize, totalChildQuesSize, childScoreAll))
        }
        /******************************************************************************************/
    }


    //实现答题卡弹窗
    private fun showAnswerSheetDialog() {
        val dialog = AibkPreviewAnswerSheetDialog(this, this, paperPreviewInfor!!, typeListPosition)
        dialog.show()
        dialog.setClickDialogListener(object : onClickDialogListener {

            override fun onSortIndexClick(sortIndex: String) {
                dialog.dismiss()
                var parentVpPosition = PreviewInforIndexHelp.SortIndex_return_ParentVpPosition(paperPreviewInfor!!, sortIndex)
                VpPreview.setCurrentItem(parentVpPosition, true)

                var index_A = PreviewInforIndexHelp.SortIndex_return_IndexA(paperPreviewInfor!!, sortIndex)
                var typeNo = paperPreviewInfor!!.TypeList[index_A].TypeNo
                if (typeNo == "k") {//k：阅读综合
                    val fragment = fragmentList!![parentVpPosition] as PreviewFragmentZht
                    fragment.jumpToSortIndex(sortIndex)
                } else if (typeNo == "x" || typeNo == "m") {//x:听力匹配,m:普通匹配题
                    val fragment = fragmentList!![parentVpPosition] as PreviewFragmentPpt
                    fragment.fragmentJumpToSortIndex(sortIndex)
                } else if (typeNo == "L" || typeNo == "E" || typeNo == "F" || typeNo == "D") {//听力选择，听力判断，阅读选择
                    val fragment = fragmentList!![parentVpPosition] as PreviewFragmentXzt
                    fragment.fragmentJumpToSortIndex(sortIndex)
                } else if (typeNo == "Q" || typeNo == "b" || typeNo == "d"
                        || typeNo == "X" || typeNo == "g" || typeNo == "V"
                        || typeNo == "G") {//Q:阅读填空,X:阅读简答,G:听力简答,
                    val fragment = fragmentList!![parentVpPosition] as PreviewFragmentJdt
                    fragment.fragmentJumpToSortIndex(sortIndex)
                } else if (typeNo == "H") {//H:复合写作
                    val fragment = fragmentList!![parentVpPosition] as PreviewFragmentFhxz
                    fragment.fragmentJumpToSortIndex(sortIndex)
                } else if (typeNo == "C") {//C:完形选择
                    val fragment = fragmentList!![parentVpPosition] as PreviewFragmentWxxz
                    fragment.fragmentJumpToSortIndex(sortIndex)
                } else if (typeNo == "N" || typeNo == "S") { //N:普通填空题  S：听力填空题
                    val fragment = fragmentList!![parentVpPosition] as PreviewFragmentTkt
                    fragment.fragmentJumpToSortIndex(sortIndex)
                }

            }

            override fun onDismissClick() {
                dialog.dismiss()
            }

        })
    }

    override fun onPause() {
        super.onPause()
        toolPauseAudio()
    }

    override fun onClick(v: View?) {
        when (v?.id) {
            R.id.BtnBack -> {
                toolPauseAudio()
                finish()
            }
            R.id.SBtnAnswerSheet -> {
                toolPauseAudio()
                showAnswerSheetDialog()
            }
            R.id.SBtnErrorRecovery -> {
                toolPauseAudio()
                quesListPosition = PreviewInforIndexHelp.QuesPosition_return_QuesListPosition(paperPreviewInfor!!, vpQuesPosition)
                val quesId = paperPreviewInfor!!.TypeList[typeListPosition].QuesList[quesListPosition].QuesID
                ActivityErrorRecovery.launch(this,quesId)
            }
            R.id.TvQuesInfor -> {
                quesScoreInfor = TvQuesInfor.text.toString()
                val mTextPaint: TextPaint = TvQuesInfor.paint
                mTextPaint.textSize = TvQuesInfor.textSize
                val mTextViewWidth = mTextPaint.measureText(quesScoreInfor).toInt()
                val mTvQuesInforWidth = TvQuesInfor.width - DensityUtils.dp2px(this, 20f)
                if (mTextViewWidth > mTvQuesInforWidth) { //超出一行
                    ShowDialogTools.showQuesScoreInofrDialog(this, quesScoreInfor)
                }
            }
        }
    }

    //暂停一切音频播放
    private fun toolPauseAudio() {
        if (paperPreviewInfor != null) {
            var typeNo = paperPreviewInfor!!.TypeList[typeListPosition].TypeNo
            if (typeNo == "x") {//x:听力匹配
                val fragment = fragmentList!![vpQuesPosition] as PreviewFragmentPpt
                fragment.pauseAudio()
                fragment.pauseChildAudio()
                fragment.audioTrackerStop()
            } else if (typeNo == "L" || typeNo == "E" || typeNo == "F") {//听力选择，听力判断
                val fragment = fragmentList!![vpQuesPosition] as PreviewFragmentXzt
                fragment.pauseAudio()
                fragment.pauseChildAudio()
                fragment.audioTrackerStop()
            } else if (typeNo == "G") {//G:听力简答,
                val fragment = fragmentList!![vpQuesPosition] as PreviewFragmentJdt
                fragment.pauseAudio()
                fragment.pauseChildAudio()
                fragment.audioTrackerStop()
            } else if (typeNo == "S") { // S：听力填空题
                val fragment = fragmentList!![vpQuesPosition] as PreviewFragmentTkt
                fragment.pauseAudio()
                fragment.pauseChildAudio()
                fragment.audioTrackerStop()
            } else if (typeNo == "f") {
                val fragment = fragmentList!![vpQuesPosition] as PreviewFragmentZw
                fragment.pauseAudio()
                fragment.pauseChildAudio()
                fragment.audioTrackerStop()
            } else if (typeNo == "H") {
                val fragment = fragmentList!![vpQuesPosition] as PreviewFragmentFhxz
                fragment.pauseAudio()
                fragment.pauseChildAudio()
                fragment.audioTrackerStop()
            }
        }
    }
}